package com.huaxin.device.listener;

import com.huaxin.device.event.AlarmTemplateUpdatedEvent;
import com.huaxin.device.feignClients.SysFeignService;
import com.huaxin.device.service.DeviceAlarmConfigService;
import com.huaxin.device.task.AlarmTaskScheduler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class AlarmTemplateUpdateListener {
    private final DeviceAlarmConfigService deviceAlarmConfigService;
    private final SysFeignService sysFeignService;
    private final AlarmTaskScheduler taskScheduler;

    @EventListener
    @Async
    public void handleAlarmTemplateUpdate(AlarmTemplateUpdatedEvent event) {
        String templateId = event.getTemplateId();
        List<String> deviceIds = deviceAlarmConfigService.getDeviceIdsByTemplate(templateId);

        log.info("模板 {} 更新，需刷新 {} 个关联设备", templateId, deviceIds.size());

        // 从字典获取检测周期（如：0/30 * * * * ? 每30秒）
        String cronExpression = sysFeignService.getAlarmDetectInterval();
        for (String deviceId : deviceIds) {
            taskScheduler.cancelDevice(deviceId);
            taskScheduler.scheduleDevice(deviceId, cronExpression);
        }
    }
}